<!-- 注册
 1. vue始终在用双向绑定的思想来准备前后端交互，每一个vue都会定义好变量给 表单（form）或者表格（table）中的html元素的值绑定
-->
<template>
  <div><!-- element组件库的Dialog对话框默认可以通过点击 modal 关闭 Dialog，即点击空白处弹框可关闭。 -->
    <!-- :visible.sync 子组键改变父组件的值 控制子组件的显示-->
    <el-dialog title="标题名" :visible.sync="addDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
      <!--<el-upload class="avatar-uploader"-->
                 <!--:action="videoUploadUrl"-->
                 <!--:file-list="videofileList"-->
                 <!--:limit="1"-->
                 <!--v-bind:data="{FoldPath:'上传目录',SecretKey:'安全验证'}"-->
                 <!--:on-progress="uploadVideoProcess"-->
                 <!--:on-success="handleVideoSuccess"-->
                 <!--:before-upload="beforeUploadVideo"-->
                 <!--:on-remove="removeVideo">-->
        <!--<video v-if="editForm.videoUrl" ref="video"-->
               <!--:src="editForm.videoUrl"-->
               <!--class="avatar video-avatar videoBox"-->
               <!--controls="controls"> 您的浏览器不支持视频播放-->
        <!--</video>-->
        <!--<i v-if="!editForm.videoUrl" class="el-icon-plus avatar-uploader-icon"></i>-->
      <!--</el-upload>-->
      <el-form   label-width="120px"  ref="addTeacherUploadForm">
<!-- 代码中的1表示第几个 和引入js的type变量对应 -->
      <el-form-item label="头像">
        <el-upload
          class="upload"
          :action="getUploadUrl"
          list-type="picture-card"
          :limit="1"
          accept="image/*"
          :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'addTeacherUploadForm','head')}"
          :on-remove="(file,fileList)=>{imgHandleRemove(1,this)}"
          :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
          :auto-upload="false"
          :file-list="fileList[0]"
          ref="file1">
          <i class="el-icon-plus"></i>
        </el-upload>
        <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
      </el-form-item>

      </el-form>
    <el-form  :model="teacher" label-width="120px" :rules="addTeamRules" ref="addTeamForm">
       <el-form-item label="教师名称" prop="tname">
         <el-col :span="16">
          <el-input v-model="teacher.tname" placeholder="请填写教师姓名"></el-input>
         </el-col>
       </el-form-item>
      <el-form-item  label="性别">
        <el-col :span="8">
          <el-radio label="男" v-model="teacher.sex">男</el-radio><el-radio label="女" v-model="teacher.sex">女</el-radio>
        </el-col>
      </el-form-item>
      <el-form-item label="出生日期">
        <el-col :span="16">
        <el-date-picker
          v-model="teacher.birthday"
          align="right"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions">
        </el-date-picker>
        </el-col>
     </el-form-item>
      <el-form-item label="参加工作日期">
        <el-col :span="16">
        <el-date-picker
          v-model="teacher.jointime"
          align="right"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions">
        </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="籍贯">
      <el-cascader
        size="large"
        :options="options"
        v-model="selectedOptions"
        @change="handleChange"
      >
      </el-cascader>

      </el-form-item>
    </el-form>
    <span>
      <el-button type="success" @click="addTeacher('addTeamForm')">注册</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import rules from "../../../../static/js/validator/rules.js"
  import utils from "../../../../static/js/utils/upload.js"
  import api from "../../../../axios/api"
  import { regionData, CodeToText } from "element-china-area-data";
    export default {
      name: "addTeam",
      data(){
        return {
          //行政区使用
          options: regionData,
          selectedOptions: [],
          //行政区使用结束
          //日历使用
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
            shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }, {
              text: '一周前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
              }
            }]
          },
          //日历使用结束
          teacher:{tname:"",sex:"",birthday:"",jointime:"",area:"","imgsrc":""},
          addDialogIsShow: false,
          addTeamRules:{tname:[{required:true,message:"教师名称不能为空",trigger:'blur'},
              {max:20,min:2,message:'长度异常 长度在2-20之间',trigger:'blur'},{pattern:/^[\u0391-\uFFE5A-Za-z]+$/,message:'球队名称必须为中文',trigger:'blur'}]},
         //上传使用
          fileList: [[],[],[]], //缓存区文件
          uploadFile:[[],[],[]], //  上传用文件
          formData:{files:[]},
          imagesUp:null,
          //上传使用结束
        }
      },
      methods: {
        addTeacher:function(addTeamForm){
          this.$refs[addTeamForm].validate(valid => {//此处refs对象和标签上的ref对应
            if (valid) {
              //如果通过验证 to do...
              console.log(this.teacher);
              alert(this.$store.state.host);
              //alert(this.teacher.tname+"添加成功");
              this.submitAddTeacher();
              this.handleClose();
            } else {
              console.log('error submit!!')
              return false
            }
          })},
        //页面初始化时加载的事件
        init() {
          this.addDialogIsShow = true;
        },

        //关闭页面
        handleClose() {
          this.addDialogIsShow = false;
          //给父组件传参
          this.$emit("addDialogIsShow", this.addDialogIsShow);
        },
        //行政区使用
        handleChange() {
          var loc = "";
          var regCode = "";
          for (let i = 0; i < this.selectedOptions.length; i++) {
            loc += CodeToText[this.selectedOptions[i]];
            regCode =this.selectedOptions[i]
          }
         console.log(loc);
          console.log(regCode);
          this.teacher.area = loc+","+regCode;
        },
        //行政区使用结束
        imghandleBeforeUpload(file,type,vm) {

          return utils.UPLOAD.Upload().handleBeforeUpload(file,type,vm);
        },
        imgHandleChange(file, fileList, type,vm,modelName,name) {
          if(vm.fileList[type].length!=0){
            alert("请先删除再提交")
          }
             return utils.UPLOAD.Upload().handleChange(file, fileList, type,vm,modelName,name);
        },
        imgHandleRemove(type,vm) {

          return utils.UPLOAD.Upload().handleRemove( type,vm);
        },



        handleUpSuccess(response, file, fileList) {
          if (response.code == 200) {
            this.ruleForm.cardUpImg = response.data[0];
            this.imagesUp = response.data;
            this.hideUp = fileList.length == 1;
            this.$message.success(response.msg);
          }
        },

        //视频成功上传的回调
        handleVideoSuccess(response, file, fileList){
          this.videoFlag = false;//隐藏进度条
          this.videoUploadPercent = 0;//进度重置为0
          if (file.status == 'success' ) {
            let videoId = JSON.parse(response.data).fileId;//保存video的id，用于拼接
            this.$api.getPublicFileUrl().then(res => {
              this.publicFileUrl = res.data.data
              this.editForm.videoUrl = this.publicFileUrl + '/' + videoId
              console.log(this.editForm.videoUrl)
            })
          } else {
            this.$message.info("上传失败，请重新上传");
          }
        },
        uploadImg:function(modelName,name){
          //  使用formdata格式
          let formData = new FormData();
          formData.append("model",modelName);//图片上传子目录
          console.log(formData);
          console.log(this.formData.files[name]);
          if (this.formData.files[name]) {
            formData.append("file", this.formData.files[name]);
          }
          console.log("----------------------------");
          console.log(formData);
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios(this.$store.state.host+"/uploadImg",formData,"post",{headers: { "Content-Type": "multipart/form-data" }})
            .then(dto=>{this.$message.info (dto.msg);
            if(dto.code==200){
              this.teacher.imgsrc = dto.obj;
            }
            });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        submitAddTeacher:function(){
          api.setDataFromAxios(this.$store.state.host+"/teacherController/addTeacher",this.teacher,"post")
            .then(dto=>{
            alert(dto.msg);
            });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        }
      },
      computed:{
        getUploadUrl(){
          return      this.$store.state.host+"/uploadImg";
        }
      },

      //监听
      watch: {
        dialogisShow(newValue, oldValue) {
          this.addDialogIsShow = newValue;
        }
      }

      }
</script>

<style scoped>

</style>
